//
//  Dictionary+SGExtension.swift.swift
//  QingLiuSwift
//
//  Created by xyanl on 2024/11/11.
//  Copyright © 2024 考拉🐨. All rights reserved.
//

import Foundation

extension Dictionary: SpadgerCompatible {}

extension Dictionary {
    
    /// 检验字典里面是否有这个 key
    func hasKey(_ key: Key) -> Bool {
        index(forKey: key) != nil
    }
    
    /// 检验 Dictionary 中是否存在 key 对应的值
    /// - Parameter key: 待检验的 key
    /// - Returns: 检验结果的布尔值
    func hasValue(_ key: Key) -> Bool {
        self[key] != nil
    }
    
    
    /// 字典 转换为 JSON字符串
    func toJSONString() -> String? {
        if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions()) {
            if let jsonStr = String(data: jsonData, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
                return String(jsonStr)
            }
        }
        return nil
    }
    
    /// 字典 转换成 url 拼接的参数
    func toQueryString() -> String? {
        let dictionary = self as! [String: Any]
        var components = URLComponents()
        components.queryItems = dictionary.map { key, value in
            let escapedKey = key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? key
            let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "\(value)"
            return URLQueryItem(name: escapedKey, value: escapedValue)
        }
        return components.percentEncodedQuery
    }
}

